/*
 * Copyright © 2020-2021 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springboot.mbp.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * MybatisPlusConfig。
 *
 * @author Denvie
 * @date 2021/7/1
 * @since 1.0.0
 */
@Slf4j
@Configuration
public class MybatisPlusConfig {
    /**
     * 配置默认的Id生成器。
     */
    @Bean
    @ConditionalOnMissingBean(IdentifierGenerator.class)
    public IdentifierGenerator identifierGenerator() {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            log.debug("init IdentifierGenerator with InetAddress: " + localhost);
            return new DefaultIdentifierGenerator(localhost);
        } catch (UnknownHostException e) {
            return new DefaultIdentifierGenerator(5L, 5L);
        }
    }

    /**
     * 配置Mybatis-Plus的分页插件。
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}
